package com.huamao.niceman.scrollviewpager.triangleviewpagerindicator;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.huamao.niceman.scrollviewpager.R;

import java.util.List;

/**
 * Created by LuanXianSheng on 2017/6/6.
 */

public class ViewPagerIndicator extends LinearLayout {
    private Paint mPaint ;//画笔
    private Path mPath ;// 绘制三角形的路径
    private int mTriangleWidth ;// 三角新的宽度
    private int mTriangleHeight ;// 三角形的高度
    private static  final float RADIO_TRIANGLE_WIDTH =1/6f ; //三角形的底边宽占整个tag的1/6 ;
    private  final int DIMENSION_TRIANGLE_MAX_WIDTH = (int) (getScreenWidth()/3*RADIO_TRIANGLE_WIDTH); //三角形的底边的最大宽度;
    private int mInitTranslationX ;//初始的偏移位置
    private int mTranslationX;//运动时的偏移位置
    private int mTabVisibleCount; // 可见的tab数量
    private static final int COUNT_DEFAULT = 4; // 默认的tab数量
    private List<String> mTitles ;//tab的的集合
    private static final int COLOR_TEXT_NORMAL=0x77FFFFFF ;
    private static final int COLOR_TEXT_HIGHLIGHT=0xFFFFFFFF ;
    private ViewPager mViewPager ;//设置关联的ViewPager

    /**
     * 由于该自定义组建中关联的viewwpager中的滑动监听事件被占用
     * 故此对外提供了一个通过这个组件监听viewpager的滑动事件，也就是说
     * 在外部想要监听viewpager的滑动事件只需实现这个接口就OK
     */
    public interface  PageOnChangeListener{
        void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
        void onPageSelected(int position);
        void onPageScrollStateChanged(int state);
    }
    public PageOnChangeListener mListener ;


    public ViewPagerIndicator(Context context) {
        this(context,null);
    }
    public ViewPagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        //从自定属性中获取可见的tab数量
      TypedArray array =  context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator) ;
        mTabVisibleCount = array.getInt(R.styleable.ViewPagerIndicator_visible_tab_count,COUNT_DEFAULT);
        if (mTabVisibleCount < 0){
            mTabVisibleCount= 4 ;
        }
        array.recycle();
        //初始化画笔
        mPaint = new Paint() ;
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.parseColor("#ffffff"));
        mPaint.setStyle(Paint.Style.FILL); //样式填充 就是实心的
        mPaint.setPathEffect(new CornerPathEffect(3)); //三角形的角稍微弯曲（为了防止三角形的太尖锐）
    }
    /**
     * 适用于需要知道控件宽度或者根据控件的宽高去设置一些宽高时都可以在这个方法里面搞事情
     * 只要控件的宽高发生变化都会回调这个方法
     * @param w
     * @param h
     * @param oldw
     * @param oldh
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mTriangleWidth = (int) (w/mTabVisibleCount*RADIO_TRIANGLE_WIDTH);
        mTriangleWidth = Math.min(mTriangleWidth,DIMENSION_TRIANGLE_MAX_WIDTH) ;
        mInitTranslationX = w/mTabVisibleCount/2-mTriangleWidth/2;
        initTriangle();
    }
    /**
     * 初始化三角形
     */
    private void initTriangle() {
        mTriangleHeight = mTriangleWidth/2 ;
        mPath = new Path() ;
        mPath.moveTo(0,0);
        mPath.lineTo(mTriangleWidth,0);
        mPath.lineTo(mTriangleWidth/2,-mTriangleHeight);
        mPath.close();
    }
    /**
     * 开始绘制
     * @param canvas
     */
    @Override
    protected void dispatchDraw(Canvas canvas) {
        canvas.save() ;
        canvas.translate(mInitTranslationX+mTranslationX,getHeight()+2);
        canvas.drawPath(mPath,mPaint);
        canvas.restore();
        super.dispatchDraw(canvas);
    }

    /**
     * 指示器随手指滚动（该方法可以是在viewpager的滚动监听里面设置）
     * @param position
     * @param offset
     */
    public void scroll(int position,float offset){
        int tagWidth = getWidth()/mTabVisibleCount;
//        int tagWidth = getScreenWidth()/mTabVisibleCount;
        mTranslationX = (int) (tagWidth*offset + position*tagWidth) ;//具体的自己画图
        //容器滚动
        if (position >= (mTabVisibleCount - 1) && offset > 0 && getChildCount() > mTabVisibleCount){
            if (mTabVisibleCount != 1){
                this.scrollTo((position-(mTabVisibleCount-1))*tagWidth + (int)(offset*tagWidth),0);
            }else {
                this.scrollTo(position*tagWidth + (int)(offset*tagWidth),0);
            }
        }
        invalidate(); //重绘

    }

    /**
     * 在xml里面加载完后回调这个方法
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int cCount = getChildCount() ;
        if (cCount == 0)return ;
        for (int i = 0;i < cCount;i++){
            View view = getChildAt(i) ;
            LinearLayout.LayoutParams lp = (LayoutParams) view.getLayoutParams();
            lp.weight = 0 ;
            lp.width = getScreenWidth()/mTabVisibleCount ;
            view.setLayoutParams(lp);
        }
        setItemClickEvent();
    }
    /**
     * 获取屏幕的宽度
     * @return
     */
    private int getScreenWidth(){
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics() ;
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

     /**
     * 设置可见的tab数量（注意需要在setTabItemTitles（）方法前调用）
     * @param count
     */
    public void setVisbleTabCount(int count){
        mTabVisibleCount = count ;
    }

    /**
     * 通过传递过来的集合创建tab
     * @param titles
     */
    public void setTabItemTitles(List<String> titles){
        if (titles != null && titles.size()> 0){
            this.removeAllViews();
            mTitles = titles ;
            for (String title:mTitles){
                addView(generateTextView(title));
            }
            setItemClickEvent();
        }

    }

    /**
     * 根据title创建tab
     * @param title
     * @return
     */
    private View generateTextView(String title) {
        TextView tv = new TextView(getContext()) ;
        LinearLayout.LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT) ;
        lp.width = getScreenWidth()/mTabVisibleCount ;
        tv.setText(title);
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,16);
        tv.setTextColor(COLOR_TEXT_NORMAL);
        tv.setLayoutParams(lp);
        return tv;
    }

    /**
     * 设置相关联的viewpager
     * @param viewPager
     */
    public void setViewPager(ViewPager viewPager,int pos){
        mViewPager = viewPager ;
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                scroll(position,positionOffset);
                if (mListener != null){
                    mListener.onPageScrolled(position,positionOffset,positionOffsetPixels);
                }
            }
            @Override
            public void onPageSelected(int position) {
                highLightTextview(position);
                if (mListener != null) {
                    mListener.onPageSelected(position);
                }

            }
            @Override
            public void onPageScrollStateChanged(int state) {
                if (mListener != null){
                    mListener.onPageScrollStateChanged(state);
                }
            }
        });
        //设置显示当前的fragment
        mViewPager.setCurrentItem(pos);
        highLightTextview(pos);
    }
    public void setOnPageChangeListener(PageOnChangeListener listener){
        mListener = listener ;
    }

    /**
     * 选中的tab中字体高亮
     * @param pos
     */
    private void highLightTextview(int pos){
        resetTextviewColor() ;
        View view = getChildAt(pos) ;
        if (view instanceof TextView){
            ((TextView)view).setTextColor(COLOR_TEXT_HIGHLIGHT);
        }
    }
    /**
     * 重置文本颜色
     */
    private void resetTextviewColor(){
        for (int i = 0; i< getChildCount();i++){
            View view = getChildAt(i) ;
            if (view instanceof TextView){
                ((TextView)view).setTextColor(COLOR_TEXT_NORMAL);
            }
        }
    }

    /**
     * 点击选择
     */
    private void setItemClickEvent(){
        int cCount = getChildCount() ;
        for (int i = 0; i <cCount;i++){
            final int j = i ;
            View view = getChildAt(i);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mViewPager.setCurrentItem(j);
                }
            });
        }
    }
}
